package com.scau.jansing.util;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.Match;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by jansing on 2015/10/23.
 */
public class CommonUtil {

    /**
     * 去掉字符串
     * todo 重命名
     *
     * @param str
     * @return
     */
    public static String remove01(String str) {
        Pattern pattern = Pattern.compile("\"[\\s\\S]*?\"");
        Matcher matcher = pattern.matcher(str);
        return matcher.replaceFirst("");
    }

    /**
     * 去掉单行注释
     * todo 重命名
     *
     * @param str
     * @return
     */
    public static String remove02(String str) {
        Pattern pattern = Pattern.compile("//[\\s\\S]*");
        Matcher matcher = pattern.matcher(str);
        return matcher.replaceFirst("");
    }

    /**
     * 去掉多行注释，在这之前应先去掉字符串
     * todo 重命名
     *
     * @param str
     * @param bf
     * @return
     * @throws IOException
     */
    public static String remove03(String str, BufferedReader bf) throws IOException {
        //存在于一行
        Pattern oneLinePattern = Pattern.compile("/\\*{1,2}[\\s\\S]*?\\*/");
        Matcher oneLineMatcher = oneLinePattern.matcher(str);
        if (oneLineMatcher.find()) {
            return oneLineMatcher.replaceFirst("");
        }
        //存在于多行
        StringBuilder result = new StringBuilder();
        Pattern headPattern = Pattern.compile("/\\*{1,2}[\\s\\S]*");
        Matcher headMatcher = headPattern.matcher(str);
        result.append(headMatcher.replaceAll(""));
        Pattern tailPattern = Pattern.compile("[\\s\\S]*?\\*/");
        while (str != null && !tailPattern.matcher(str).find()) {
            str = bf.readLine();
        }
        result.append(tailPattern.matcher(str).replaceAll(""));
        return result.toString();
    }

    public static String removeInvalid(String str, BufferedReader bf) throws IOException {
        if (!str.contains("\"") && !str.contains("//") && !str.contains("/*")) {
            return str.trim();
        }
        for (int i = 0; i < str.length(); ) {
            switch (str.charAt(i)) {
                case '\"':
                    str = remove01(str);
                    break;
                case '/':
                    i++;
                    if (str.charAt(i) == '/') {
                        str = remove02(str);
                    } else if (str.charAt(i) == '*') {
                        str = remove03(str, bf);
                    }
                    break;
                default:i++;
            }
        }
        return str.trim();
    }

}
